package com.xxq.semester.service.impl.question;

import com.xxq.semester.entity.question.Questions;
import com.xxq.semester.mapper.QuestionsMapper;
import com.xxq.semester.service.question.IQuestionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@Service
@Slf4j
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper, Questions> implements IQuestionsService {

    @Override
    public List<Questions> selectAllQuestions() {
        log.info("开始查询所有试题");
        try {
            // 使用自定义查询方法，确保使用resultMap正确映射options字段
            List<Questions> questions = baseMapper.selectAllQuestions();
            return getQuestions(questions);
        } catch (Exception e) {
            log.error("查询所有试题时发生异常", e);
            return null;
        }
    }

    private List<Questions> getQuestions(List<Questions> questions) {
        log.info("查询到试题数量: {}", questions != null ? questions.size() : 0);
        if (questions != null && !questions.isEmpty()) {
            log.info("第一个试题内容: {}", questions.get(0));
            log.info("第一个试题options: {}", questions.get(0).getOptions());
        }
        return questions;
    }

    @Override
    public Questions selectQuestionsByQuestionId(int id) {
        log.info("开始查询试题ID: {}", id);
        try {
            // 使用自定义查询方法，确保使用resultMap正确映射options字段
            Questions question = baseMapper.selectQuestionsByQuestionId(id);
            if (question != null) {
                log.info("查询到试题: {}", question);
                log.info("试题options: {}", question.getOptions());
            }
            return question;
        } catch (Exception e) {
            log.error("查询试题时发生异常", e);
            return null;
        }
    }

    @Override
    public List<Questions> selectQuestionsByCreatorId(int creatorId) {
        log.info("开始查询创建者ID为 {} 的试题", creatorId);
        try {
            // 使用自定义查询方法，确保使用resultMap正确映射options字段
            List<Questions> questions = baseMapper.selectQuestionsByCreatorId(creatorId);
            return getQuestions(questions);
        } catch (Exception e) {
            log.error("查询创建者试题时发生异常", e);
            return null;
        }
    }

    @Override
    public boolean addQuestion(Questions question) {
        return save(question);
    }

    @Override
    public boolean deleteQuestionById(int questionId) {
        return removeById(questionId);
    }

    @Override
    public boolean updateQuestion(Questions question) {
        return updateById(question);
    }

}